<?php
namespace app\admin\controller;
use AlibabaCloud\Aas\V20150701\DeleteAccessKeyForAccount;
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Menu;
use think\Request;
use think\Session;


class Admins extends Base
{
    /*
     * 后台加载首页用户中心
     */
    public function admin(){
        $user = $this->user_info();
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$user,
        );
        return view("admin",$data);
    }
    /*
     * 用户列表
     */
    public function lists(){
        $user = $this->user_info();
        $users = collection(Admin::select())->toArray();

        foreach($users  as $key=>$val){
            if($val['jurisdiction']!=''){
                $where = "id in (".$val['jurisdiction'].") and pid = 0";
                $jurisdiction = Menu::where($where)->order("sort asc")->select();
                $jurisdiction = collection($jurisdiction)->toArray();
                $users[$key]['jurisdiction'] = $jurisdiction;
            }else{
                $users[$key]['jurisdiction'] = array();
            }

            foreach ($jurisdiction as $k=>$v){
                if($val['jurisdiction']!=''){
                    $where2 = "id in (".$val['jurisdiction'].") and pid = ".$v['id'];
                    $jurisdictionTow = Menu::where($where2)->select();
                    $jurisdictionTow = collection($jurisdictionTow)->toArray();
                    $users[$key]['jurisdictiontow'][$k] = $jurisdictionTow;
                }else{
                    $users[$key]['jurisdictiontow'][$k] = array();

                }

            }
        }

        $data = array(
            "setting" => $this->getAllSetting(),
            "user" =>$user,
            "list" =>$users,
        );
        return view("list",$data);
    }
    /*
     * 添加用户
     */
    public function addform()
    {
        $user = $this->user_info();
        $menu = Menu::where(array("status"=>1,"pid"=>0))->order("sort asc")->select();
        foreach($menu as $key => $val){
            $menutow = Menu::where(array("status"=>1,"pid"=>$val['id']))->select();
            $menutow = collection($menutow)->toArray();
            $menu[$key]['tow']=$menutow;
        }
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$user,
            "menu" =>$menu,
        );
        return view("addform",$data);
    }
    /*
     * 执行添加操作
     */
    public function adds(Request $request){
        $data = $request->post();
        $data['password'] = md5($data['password']);
        $data['create_time'] = time();
        $data['create_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['jurisdiction'] = substr($data['jurisdiction'],0,-1);
        //查询用户名是否重复
        $res = Admin::where(array("username"=>$data['username']))->count();
        if($res > 0){
            $this->error("该用户名已经存在!请更换用户名再试！");
            exit();
        }
        if(Admin::insert($data)){
            $this->success("添加成功","Admins/lists");
        }else{
            $this->error("添加失败");
        }
    }
    /*
     * 修改用户
     */
    public function update(Request $request){
        $id = $request->get("id");
        $user = $this->user_info();
        //查询当前需要修改的用户
        $admin = Admin::where(['id'=>$id])->find();
        //修改具有权限的栏目为数组
        $admin['jurisdiction'] = explode(",",$admin['jurisdiction']);
        $admins = collection($admin)->toArray();
        //查询所有可用的后台爱栏目
        $menu = Menu::where(array("status"=>1,"pid"=>0))->order("sort asc")->select();
        foreach($menu as $key => $val){
            $menutow = Menu::where(array("status"=>1,"pid"=>$val['id']))->select();
            $menutow = collection($menutow)->toArray();
            $menu[$key]['tow']=$menutow;
        }
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$admin,
            "menu" =>$menu,
            "isSelf"=> $id == $user['id'] ? 1 : 2
        );
        return view("update",$data);
    }
    /*
     * 执行修改
     */
    public function toupdate(Request $request){
        $user = $this->user_info();
        $data = $request->post();
        $data['jurisdiction'] = substr($data['jurisdiction'],0,-1);
        if (!empty($data['password'])){
            $data['password'] = md5($data['password']);
        }
        if(Admin::update($data)){
            //如果是当前用户直接修改Session值
            if($data['username'] == $user['username']){
                $newUser = Admin::where(array('id'=>$user['id']))->find();
                Session::delete("user_info");
                Session::set("user_info",$newUser);
            }
            $this->success("修改成功","Admins/lists");
        }else{
            $this->error("修改失败","Admins/update");
        }
    }
    /*
     * 删除
     */
    public function deletes(Request $request){
        $id = $request->post("id");
        if(Admin::destroy(["id"=>$id])){
            $this->success("删除成功","Admins/lists");
        }else{
            $this->error("删除失败");
        }
    }

  //上传文件
  public function upload(Request $request){
    //接收上传的文件
    $file = $this->request->file('file');
    if(!empty($file)){
      //图片存的路径
      $imgUrl= ROOT_PATH . 'public' . DS .'static'. DS .'admin'. DS .'uploads'. DS .'headphoto';

      // 移动到框架应用根目录/public/uploads/ 目录下

      $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->rule('uniqid')->move($imgUrl);
      $error = $file->getError();
      //验证文件后缀后大小
      if(!empty($error)){
        dump($error);exit;
      }
      if($info){
        // 成功上传后 获取上传信息

        //获取图片的名字
        $imgName = $info->getFilename();
        //获取图片的路径
        $photo= $imgName;

      }else{
        // 上传失败获取错误信息
        $file->getError();
      }
    }else{
      $photo = '';
    }
    if($photo !== ''){
      return ['code'=>1,'msg'=>'成功','photo'=>$photo];
    }else{
      return ['code'=>404,'msg'=>'失败'];
    }
  }

    //修改个人信息
    public function updateAdmin(Request $request){
        $user = $this->user_info();
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$user,
        );
        return view("updateAdmin",$data);
    }

    public function toUpdateAdmin(Request $request){
        $user = $this->user_info();
        $data = $request->post();
        $data["id"] = $user['id'];
        if($request->post("username") != $user['username']) {
            $resname = Admin::where(array("username" => $request->post("username")))->find();
        }else{
            $resname = false;
        }
        //判断用户是否正确可以登录
        if(!$resname){
            if(Admin::update($data) !== false){
                $this->success("修改信息成功，请重新登录","Login/Logins");
            }else{
                $this->error("修改信息失败","Set/toUpdateAdmin");
            }
        }else{
            $this->error("用户名已经存在");
        }
    }
    //修改密码
    public function setpassword(){
        $user = $this->user_info();
        $data = array(
            "setting" => $this->getAllSetting(),
        );
        return view("setpassword",$data);
    }
    //执行修改密码
    public function toSetPassword(Request $request){
        $oldpassword = $request->post("oldpassword");

        $password = $request->post("password");
        //判断用户是否正确可以登录
        $user = $this->user_info();
        if(md5($oldpassword) == $user['password']){
            if(Admin::update(array("id"=>$user['id'],"password"=>md5($password)))){
                $this->success("密码修改成功，请重新登录","Login/Logins");
            }else{
                $this->error("密码修改失败","Set/setpassword");
            }
        }else{
            $this->error("旧密码错误");
        }
    }

}
